package com.framework.utils.property;

import java.io.File;

/**
 * 
 * <p>Description: 检查文件是否发生变动</p>
 * @since 2016年10月20日
 * @author 张飞
 * <p>Copyright:Copyright(c)2016</p>
 */
public abstract class FileWatchDog extends Thread {

	public final static long DEFAULT_DELAY = 60000;

	protected String fileName;

	protected long delay = DEFAULT_DELAY;

	private File file;

	private long lastModif = 0;
	private boolean warnedAlready = false;
	private boolean interrupted = false;

	public FileWatchDog(String fileName) {
		this.fileName = fileName;
		file = new File(fileName);
		setDaemon(true);
		checkAndConfigure();
	}

	protected void checkAndConfigure() {
		boolean fileExists;
		try {
			fileExists = file.exists();
		} catch (Exception e) {
			e.printStackTrace();
			interrupted = true;
			return;
		}

		if (fileExists) {
			long l = file.lastModified();
			if (l > lastModif) {
				lastModif = l;
				doOnChange();
				warnedAlready = false;
			}
		} else {
			if (!warnedAlready) {
				warnedAlready = true;
			}
		}
	}

	public void setDelay(long delay) {
		this.delay = delay;
	}

	protected abstract void doOnChange();

	@Override
	public void run() {
		while (!interrupted) {
			try {
				Thread.sleep(delay);
			} catch (InterruptedException e) {
			}
			checkAndConfigure();
		}
	}
}
